package com.vchello.util;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.vchello.bean.user.User;

/**
 * 
 * @author power
 *
 */
public class ExportUtil {

	@SuppressWarnings("resource")
	public static void exportExcel(HttpServletResponse response, String headName, String fileName, String[] cellValue,
			List<?> list) {
		// 第一步创建workbook
		HSSFWorkbook wb = new HSSFWorkbook();
		// 第二步创建sheet
		HSSFSheet sheet = wb.createSheet(headName);
		// 第三步创建行row:添加表头0行
		HSSFRow row = sheet.createRow(0);
		HSSFCellStyle style = wb.createCellStyle();
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中
		// 第四步创建单元格

		HSSFCell[] cell = new HSSFCell[cellValue.length];
		// HSSFCell cell = null;
		for (int i = 0; i < cellValue.length; i++) {
			// cell = row.createCell(i); //第一个单元格
			// cell.setCellValue(cellValue[i]); //设定值
			// cell.setCellStyle(style); //内容居中
			cell[i] = row.createCell(i);
			cell[i].setCellValue(cellValue[i]);
			cell[i].setCellStyle(style);
		}

		// 第五步插入数据
		for (int i = 0; i < list.size(); i++) {
			Object object = list.get(i);
			if(object instanceof User) {
				userRow(list, sheet, row, object, i);
			}
		}

		try {
			OutputStream output = response.getOutputStream();
			response.reset();
			if (fileName == "") {
				fileName = "文件信息.xls";
			}
			response.setHeader("Content-Disposition",
					"attachment; filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
			response.setContentType("application/xls;charset=UTF-8");
			wb.write(output);
			output.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void userRow(List<?> list, HSSFSheet sheet, HSSFRow row, Object object, int count) {
		User user = (User) object;
		// 创建行
		row = sheet.createRow(count + 1);
		// 创建单元格并且添加数据
		row.createCell(0).setCellValue(user.getUserName());
		row.createCell(1).setCellValue(user.getType() == 1 ? "机构" : "投资人");
		row.createCell(2).setCellValue(user.getEmail());
		row.createCell(3).setCellValue(user.getPhone());
		row.createCell(4).setCellValue(user.getCreateTime());
		row.createCell(5).setCellValue(user.getLastLoginTime());
	}
}
